/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.github.pwittchen.swip.app;

import com.github.pwittchen.swip.library.rx2.Swipe;

import com.github.pwittchen.swip.library.rx2.utils.HosSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Text;
import ohos.multimodalinput.event.TouchEvent;

/**
 * rxjava实现滑动监听页面
 */
public class SwipRxAbility extends Ability {
    private Text info;
    private DirectionalLayout dirView;
    private Swipe swipe;
    private Disposable disposable;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        info = (Text) findComponentById(ResourceTable.Id_info);
        dirView = (DirectionalLayout) findComponentById(ResourceTable.Id_dir);
        Text textTitle = (Text) findComponentById(ResourceTable.Id_title1);
        textTitle.setText("滑动监听RX实现");
        swipe = new Swipe();
        dirView.setTouchEventListener(
                new Component.TouchEventListener() {
                    @Override
                    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
                        swipe.dispatchTouchEvent(touchEvent);
                        return true;
                    }
                });


        disposable =
                swipe.observe()
                        .subscribeOn(Schedulers.computation())
                        .observeOn(HosSchedulers.mainThread())
                        .subscribe(swipeEvent -> info.setText(swipeEvent.toString()));
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        safelyUnsubscribe(disposable);
    }

    private void safelyUnsubscribe(Disposable disposable) {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }
}
